﻿using System;
using System.Windows.Forms;
using System.ServiceModel;
using FormClient.MServiceReference;

namespace FormClient
{
    public partial class Form1 : Form
    {
        Callback callback;
        InstanceContext context;
        DuplexChannelFactory<IMessageService> channelFactory;
        IMessageService proxy;

        public Form1()
        {
            InitializeComponent();
            callback = new Callback();
            context = new InstanceContext(callback);
            callback.MessageReceived += callbak_MessageReceived;
            channelFactory = new DuplexChannelFactory<IMessageService>(context,"TCP");
            proxy=channelFactory.CreateChannel();
            
            
        }

        void callbak_MessageReceived(object sender, Callback.MessageReceiveArgs e)
        {
            rtbConversation.AppendText(e.Name + ":" + e.Message+"\n");
            rtbConversation.ScrollToCaret();
        }

        private void btnRegister_Click(object sender, EventArgs e)
        { 
            proxy.RegisterAsync(tbName.Text);
            MessageBox.Show("Register Complete.");
            tbName.ReadOnly = true;
        }

        private void tbMessage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13) 
            {
                proxy.SendMessageAsync(tbName.Text, tbMessage.Text);
                tbMessage.Text = string.Empty;
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            proxy.SendMessageAsync(tbName.Text, tbMessage.Text);
            tbMessage.Text = string.Empty;
        }
    }
}
